package think.thread.c07.cyclicbarrier;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierDemo {
	// 徒步需要的时间: Shenzhen, Guangzhou, Chongqing,heilongjiang
	private static int[] timeForWalk = { 5, 8, 15, 20 };
	// 自驾游
	private static int[] timeForSelf = { 1, 5, 7, 12 };
	// 旅游大巴
	private static int[] timeForBus = { 2, 4, 9, 25 };
	// 目的地
	private static String[] target = { "Shenzhen", "Guangzhou", "Chongqing",
			"Heilongjiang" };
	// 长度
	private static final int len = 4;

	static String nowTime() {// 时间格式化
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
		return sdf.format(new Date()) + ": ";
	}

	static class Tour implements Runnable {
		private int[] timeForUse;
		private CyclicBarrier barrier;
		private String tourName;
		private String[] target;

		public Tour(CyclicBarrier barrier, String tourName, int[] timeForUse,
				String[] target) {
			this.timeForUse = timeForUse;
			this.tourName = tourName;
			this.barrier = barrier;
			this.target = target;
		}

		public void run() {
			try {
				for (int i = 0; i < len; i++) {
					Thread.sleep(timeForUse[i] * 1000);
					System.out.println(nowTime() + tourName + " Reached "
							+ target[i]);
					barrier.await();// 到达中转站后等待其他旅行团
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		// 三个旅行团都到到达某一个站点后，执行下面的操作，表示都到齐了。
		Runnable runner = new Runnable() {
			public void run() {
				System.out.println("we all are here.");
			}
		};
		CyclicBarrier barrier = new CyclicBarrier(3, runner);
		// 使用线程池
		ExecutorService exec = Executors.newFixedThreadPool(3);
		exec.submit(new Tour(barrier, "WalkTour", timeForWalk, target));
		exec.submit(new Tour(barrier, "SelfTour", timeForSelf, target));
		exec.submit(new Tour(barrier, "BusTour", timeForBus, target));
		exec.shutdown();
	}
}
